package com.company.finance.ddd.domain.core.voucher.event.handler;

import com.company.finance.ddd.domain.core.voucher.VoucherService;
import com.company.finance.ddd.domain.core.voucher.enums.VoucherSendState;
import com.company.finance.ddd.domain.core.voucher.event.VoucherCreateSucceedEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Observable;


/**
 *
 * @author wanglei
 * @version $$Id: AccountingDocumentSender, v 0.1 2021/2/2 17:36 wanglei Exp $$
 */
@Slf4j
@Component
public class VoucherSucceedEventHandler implements EventHandler {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private VoucherService voucherService;

    public VoucherSucceedEventHandler(Observable observable) {
        observable.addObserver(this);
    }

    @Override
    public void update(Observable publisher, Object event) {
        if (!(event instanceof VoucherCreateSucceedEvent)) {
            return;
        }
        log.info("Event -> {}", event);

        VoucherCreateSucceedEvent succeedEvent = (VoucherCreateSucceedEvent) event;
        //TODO replace real url
        boolean sendSuccess = false;
        try {
            String result = restTemplate.getForObject("http://localhost:8081/bill/get/"
                            + succeedEvent.getBillId().toString(), String.class);
            log.info("Voucher[billId - {}] sending result -> {}", succeedEvent.getBillId(), result);
            sendSuccess = true;
        } catch (Exception e) {
            log.info("Send voucher[billId -> {}] to KingDee finance system failed. {}"
                    , succeedEvent.getBillId(), e.getMessage());
        }
        boolean finalSendSuccess = sendSuccess;
        voucherService.query(VoucherService.VoucherQueryParam.builder()
                .billId(succeedEvent.getBillId()).build())
                .forEach(voucher -> {
                    voucher.setID(succeedEvent.getVoucherId());
                    voucher.setSEND_TIME(new Date());
                    if (finalSendSuccess) {
                        voucher.setSTATE(VoucherSendState.SENT.code);
                    } else {
                        voucher.setSTATE(VoucherSendState.SEND_FAILED.code);
                        voucher.setREMARK("向金蝶财务系统发送凭证失败");
                    }
                    voucherService.getVoucherRepository().save(voucher);
                });

    }
}

